package com.tucc.hello.leetcode.no1_400.no1_200.no81_100.no82;

import com.tucc.hello.leetcode.common.ListNode;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head = ListNode.of(1, 1, 2);
        ListNode newHead = solution.deleteDuplicates(head);
        ListNode.print(newHead);
    }

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        int cur = head.val;
        ListNode next = head.next;
        ListNode pre = head;
        ListNode tail = null;
        ListNode newHead = null;
        while (next != null) {
            if (next.val == cur) {
                next = next.next;
                pre = null;
            } else {
                if (pre != null) {
                    if (newHead == null) {
                        newHead = pre;
                        tail = pre;
                    } else {
                        tail.next = pre;
                        tail = tail.next;
                    }
                }
                cur = next.val;
                pre = next;
                next = next.next;
                if (next == null) {
                    if (newHead == null) {
                        newHead = pre;
                        tail = pre;
                    } else {
                        tail.next = pre;
                        tail = tail.next;
                    }
                }
            }
        }
        if (tail != null) {
            tail.next = null;
        }
        return newHead;
    }
}
